﻿using System;
using System.Threading.Tasks;
using WebApiClientCore.Exceptions;

namespace WebApiClientCore.Attributes
{
    /// <summary>
    /// WebApiClientCore uri特性重写
    /// 请求url+httpmethod路径
    /// </summary>
    public class UriNAttribute : ApiParameterAttribute
    {
        /// <summary>
        /// OnRequestAsync
        /// </summary>
        public override Task OnRequestAsync(ApiParameterContext context)
        {
            if (context.Parameter.Index > 0)
            {
                throw new ApiInvalidConfigException("uri特性参数只能一个");
            }

            var uri = ConvertToUri(context.ParameterValue ?? throw new ArgumentNullException(context.ParameterName));
            var requestMessage = context.HttpContext.RequestMessage;
            var newUri = new Uri(uri + requestMessage?.RequestUri?.ToString());

            requestMessage.RequestUri = requestMessage.MakeRequestUri(newUri);
            return Task.CompletedTask;
        }

        #region private methods
        /// <summary>
        /// uri转换
        /// </summary>
        private static string ConvertToUri(object uriValue)
        {
            if (uriValue is Uri result)
            {
                return result.ToString();
            }

            var text = uriValue.ToString();
            if (Uri.TryCreate(text, UriKind.RelativeOrAbsolute, out result))
            {
                return result.ToString();
            }

            throw new ApiInvalidConfigException(text);
        }
        #endregion
    }
}
